package haizhi.fruitmall.service.impl;

import com.github.pagehelper.PageHelper;
import haizhi.fruitmall.dao.mapper.GoodsMapper;
import haizhi.fruitmall.exception.ResultException;
import haizhi.fruitmall.pojo.form.GoodsForm;
import haizhi.fruitmall.pojo.po.Goods;
import haizhi.fruitmall.pojo.po.GoodsExample;
import haizhi.fruitmall.service.GoodsService;
import haizhi.fruitmall.util.BeanUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * Created by richa on 2017/9/13
 */

@Service
@Transactional
public class GoodsServiceImpl implements GoodsService {

    @Autowired
    private GoodsMapper goodsMapper;

    @Override
    public Long insert(GoodsForm form) {
        Goods record = new Goods();
        BeanUtil.copyBean(form,record);
        record.setGoodsId(BeanUtil.longId());
        goodsMapper.insertSelective(record);
        return record.getGoodsId();
    }

    @Override
    public void update(GoodsForm form) {
        Goods record = this.getone(form.getGoodsId());
        if (BeanUtil.isNull(record)) { throw new ResultException("记录不存在！"); }
        BeanUtil.copyBean(form,record);
        record.setUpdateTime(BeanUtil.newTime());
        goodsMapper.updateByPrimaryKeySelective(record);
    }

    @Override
    public void delete(Long id) {
        if (BeanUtil.isNull(this.getone(id))) { throw new ResultException("记录不存在！"); }
        goodsMapper.deleteByPrimaryKey(id);
    }

    @Override
    public Goods getone(Long id) {
        if(BeanUtil.isNull(id)) { throw new ResultException("编号为空！"); }
        return goodsMapper.selectByPrimaryKey(id);
    }

    @Override
    public List<Goods> getall(GoodsForm form) {
            GoodsExample example = new GoodsExample();
            GoodsExample.Criteria criteria = example.createCriteria();
            if(BeanUtil.noEmpty(form.getBrandName())){
                criteria.andBrandNameEqualTo(form.getBrandName());
            }
            if(BeanUtil.noNull(form.getCategoryId())) {
                criteria.andCategoryIdEqualTo(form.getCategoryId());
            }
            if(BeanUtil.noNull(form.getIsSpecial())){
                criteria.andIsSpecialEqualTo(form.getIsSpecial());
            }
            if(BeanUtil.noNull(form.getOrderBy())) {
                switch (form.getOrderBy()){
                    case 3 : example.setOrderByClause("comment_times desc");break;
                    case 4 : example.setOrderByClause("create_time desc");break;
                    case 5: example.setOrderByClause("total_sales desc"); break;
                }
            }
            if(BeanUtil.noNull(form.getPageNum()) && BeanUtil.noNull(form.getPageSize())){
                PageHelper.startPage(form.getPageNum(),form.getPageSize());
            }
            return goodsMapper.selectByExample(example);
    }
}
